<?php

namespace app\common\service;

use app\api\model\AdminAuthMenu;
use app\common\model\AdminUserOauth;
use app\common\tools\Visitor;
use app\http\exception\AuthException;
use app\model\Resident;
use think\exception\DbException;
use think\Paginator;

use function md6;
use function now_time;

class AdminUserOauthService {

    /**
     * 管理员列表
     *
     * @param $request
     *
     * @return Paginator
     * @throws DbException
     */
    static public function cmsList($request) : Paginator {
        return AdminUserOauth::with([
            'groups'
        ])
                             ->keyWrod('id|name', $request)
                             ->like('name')
                             ->where('is_delete', 1)
                             ->order('create_time asc')
                             ->_paginate();
    }

    /**
     * 管理员详情
     *
     * @param $id
     *
     * @return array
     */
    static public function cmsDetail($id) : array {
        return AdminUserOauth::with(['groups'])
                             ->where('id', $id)
                             ->find()
                             ->toArray();
    }

    /**
     * 删除管理员
     *
     * @param $id
     *
     * @return bool|false
     * @throws AuthException
     * @throws \Exception
     */
    static public function cmsDelete($id) : bool {
        $admin = AdminUserOauth::build()
                               ->where('id', $id)
                               ->find();

        if ($admin['account'] === 'admin') {
            throw new AuthException('超级管理员禁止删除!');
        }
        return AdminUserOauth::build()
                             ->where('id', $id)
                             ->delete();
    }

    /**
     * 修改管理员信息
     *
     * @param $request
     *
     * @return AdminUserOauth
     */
    static public function cmsEdit($request) : AdminUserOauth {
        $id = $request['id'];
        unset($request['id']);
        return AdminUserOauth::build()
                             ->where('id', $id)
                             ->update($request);
    }

    /**
     * 添加管理员
     *
     * @param $request
     *
     * @return bool|false
     */
    static public function cmsAdd($request) : bool {
        $request['password'] = md6($request['password']);
        $request['create_time'] = now_time(time());

        return AdminUserOauth::build()
                             ->save($request);
    }

    /**
     * 修改管理员信息
     *
     * @param $id
     * @param $request
     *
     * @return AdminUserOauth
     */
    static public function resetPassword($id, $request) : AdminUserOauth {
        $new_password = md6($request['new_password'] ?? '123456');
        return AdminUserOauth::build()
                             ->where('id', $id)
                             ->update(['password' => $new_password]);
    }


}